package com.leantech.android.browser.ui.favorites.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import coil.load
import com.cscj.android.repository.db.entity.FavoritesEntity
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.ItemFavoritesBinding
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.show
import com.cscj.android.utils.BitmapUtils.asBitmap


class FavoritesAdapter(private val adapterCallback: FavoritesAdapterCallback) :
    ListAdapter<FavoritesEntity, FavoritesAdapter.FavoritesItemViewHolder>(
        diffCallback
    ) {

    companion object {
        private val diffCallback = object : ItemCallback<FavoritesEntity>() {
            override fun areItemsTheSame(
                oldItem: FavoritesEntity, newItem: FavoritesEntity
            ): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(
                oldItem: FavoritesEntity, newItem: FavoritesEntity
            ): Boolean {
                return oldItem == newItem
            }
        }

        private const val PayloadEditModeChange = 1
        private const val PayloadCheckedChange = 2

    }

    private var editMode = false
    private val checkedIds = hashSetOf<Int>()

    fun updateEditMode(on: Boolean) {
        if (on == editMode) return
        editMode = on
        notifyItemRangeChanged(0, itemCount, PayloadEditModeChange)
    }

    fun selectItems(ids: Set<Int>) {
        if (!editMode) return
        checkedIds.clear()
        checkedIds.addAll(ids)
        notifyItemRangeChanged(0, itemCount, PayloadCheckedChange)
    }

    fun selectItemsNotNotify(ids: Set<Int>) {
        if (!editMode) return
        checkedIds.clear()
        checkedIds.addAll(ids)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoritesItemViewHolder {
        val binding =
            ItemFavoritesBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return FavoritesItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: FavoritesItemViewHolder, position: Int) {
        val item = getItem(position)
        Log.e("xxxxxxxxxx", "onBindViewHolder1: ${position}   ${checkedIds.contains(item.id)}")
        holder.bind(item, editMode, checkedIds.contains(item.id), adapterCallback)
    }

    override fun onBindViewHolder(
        holder: FavoritesItemViewHolder, position: Int, payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            val item = getItem(position)
            Log.e("xxxxxxxxxx", "onBindViewHolder2: ${position}   ${checkedIds.contains(item.id)}")
            payloads.forEach { payload ->
                when (payload) {
                    PayloadEditModeChange -> {
                        holder.updateEditMode(item, editMode, adapterCallback)
                    }

                    PayloadCheckedChange -> {
                        holder.updateChecked(checkedIds.contains(item.id))
                    }

                    else -> {
                        super.onBindViewHolder(holder, position, payloads)
                    }
                }
            }
        }

    }

    interface FavoritesAdapterCallback {

        fun onFavoritesItemClick(data: FavoritesEntity, position: Int)

        fun onFavoritesItemChecked(data: FavoritesEntity, position: Int, checked: Boolean)

    }

    class FavoritesItemViewHolder(private val binding: ItemFavoritesBinding) :
        ViewHolder(binding.root) {

        fun bind(
            item: FavoritesEntity,
            editMode: Boolean,
            checked: Boolean,
            adapterCallback: FavoritesAdapterCallback
        ) {
            updateEditMode(item, editMode, adapterCallback)
            updateChecked(checked)
            val icon = item.icon?.asBitmap()
            if (icon == null) {
                binding.favicon.load(R.drawable.icon_default_link)
            } else {
                binding.favicon.load(icon)
            }
            binding.title.text = item.title
            binding.content.text = item.url
        }

        fun updateEditMode(
            item: FavoritesEntity, editMode: Boolean, adapterCallback: FavoritesAdapterCallback
        ) {
            binding.checkbox.show(editMode)
            if (editMode) {
                binding.checkbox.setOnCheckedChangeListener { _, isChecked ->
                    adapterCallback.onFavoritesItemChecked(item, bindingAdapterPosition, isChecked)
                }
            } else {
                binding.checkbox.setOnCheckedChangeListener(null)
            }
            binding.root.onThrottleClick {
                if (editMode) {
                    binding.checkbox.toggle()
                } else {
                    adapterCallback.onFavoritesItemClick(item, bindingAdapterPosition)
                }
            }
        }

        fun updateChecked(checked: Boolean) {
            binding.checkbox.isChecked = checked
        }

    }

}